﻿using System;

namespace HikvisionDemo
{
    class LoginUtils
    {

        public static int Login(string ip, int port, string username, string password) 
        {
            // 登录

            int userId = -1;

            CHCNetSDK.NET_DVR_USER_LOGIN_INFO struLogInfo = new CHCNetSDK.NET_DVR_USER_LOGIN_INFO();

            //设备IP地址或者域名
            byte[] byIP = System.Text.Encoding.Default.GetBytes(ip);
            struLogInfo.sDeviceAddress = new byte[129];
            byIP.CopyTo(struLogInfo.sDeviceAddress, 0);

            struLogInfo.wPort = ((ushort)port);//设备服务端口号

            //设备用户名
            byte[] byUserName = System.Text.Encoding.Default.GetBytes(username);
            struLogInfo.sUserName = new byte[64];
            byUserName.CopyTo(struLogInfo.sUserName, 0);

            //设备密码
            byte[] byPassword = System.Text.Encoding.Default.GetBytes(password);
            struLogInfo.sPassword = new byte[64];
            byPassword.CopyTo(struLogInfo.sPassword, 0);

            // 这里使用同步登录，异步登录需要设置回调函数来接收登录状态
            struLogInfo.bUseAsynLogin = false; //是否异步登录：0- 否，1- 是

            CHCNetSDK.NET_DVR_DEVICEINFO_V40 DeviceInfo = new CHCNetSDK.NET_DVR_DEVICEINFO_V40();

            //登录设备 Login the device
            userId = CHCNetSDK.NET_DVR_Login_V40(ref struLogInfo, ref DeviceInfo);
            if (userId < 0)
            {
                
                uint iLastErr = CHCNetSDK.NET_DVR_GetLastError(); 
                Console.WriteLine($"登录失败，用户ID={userId}，错误号={iLastErr}");
            }
            else
            {
                //登录成功
                Console.WriteLine($"登录成功，用户ID={userId}");
            }

            return userId;
        }

        public static bool Logout(int userId)
        {
            // 用户注销
            bool result = false;
            if (userId >= 0)
            {
                result = CHCNetSDK.NET_DVR_Logout(userId);
                if (result)
                {
                    Console.WriteLine($"用户{userId}注销成功");
                }
                else
                {
                    uint iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    Console.WriteLine($"用户{userId}注销失败，错误代码={iLastErr}");
                }
            }
            return result;
        }
    }
}
